package book;

import java.util.ArrayList;
import java.util.List;

/**
 * 只能存放一个元素的池子
 * @author：涂有
 * @date 2017年2月27日 下午10:21:53
 */
public class OnlyOneInPool{

	public List<String> list = new ArrayList<String>(1);
	
	public void add(String str){
		
		while(true){
			
			synchronized (list) {
			
				if(list.size() == 0){
					
					list.add(str);
					list.notifyAll();
					return;
				}else{
					
					try {
						list.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	public String get(){
		
		while(true){
			
			synchronized (list) {
				
				if(list.size() == 1){
					
					list.notifyAll();
					return list.remove(0);
				}else{
					
					try {
						list.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	public int size(){
		
		synchronized (list) {
		
			return list.size();
		}
	}
	
	static class Producer extends Thread{
		
		private OnlyOneInPool pool;
		
		public Producer(OnlyOneInPool pool) {
			
			this.pool = pool;
		}
		
		@Override
		public void run() {
			
			for(int i = 0; i < 10; i++){
				
//				synchronized (pool) {
					
					pool.add(String.valueOf(i));
					System.out.println("生产一个：" + i);
//				}
			}
		}
	} 
	
	static class Consumer extends Thread{
		
		private OnlyOneInPool pool;
		
		public Consumer(OnlyOneInPool pool) {
			
			this.pool = pool;
		}
		
		@Override
		public void run() {
			
			for(int i = 0; i < 10; i++){
				
//				synchronized (pool) {
					
					String str = pool.get();
					System.out.println("消费一个：" + str);
//				}
			}
		}
	} 
	
	public static void main(String[] args) {
		
		OnlyOneInPool pool = new OnlyOneInPool();
		Producer p = new Producer(pool);
		Consumer c = new Consumer(pool);
		p.start();
		c.start();
	}
}
